package com.application.race.manage;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.application.race.manage.action.Actions;
import com.application.room.manage.RoomManage;
import com.application.room.pojo.Room;
public class RaceroomManage  extends Thread implements Runnable {
	
	private static final Logger log = LoggerFactory
	.getLogger(RaceroomManage.class);	
	
	//Map<String,UserInfo> catchusers;
	Map<Integer,RacingRoom> rooms;
 
	//Players players;
	static final int MAX_ROOM_NUMBER=150;

	public Actions actions;
	public MapManager mapMng;
	public RaceroomManage( ){
		rooms=new HashMap<Integer,RacingRoom>();
		mapMng=new MapManager();
	}
    public static boolean gameStart=true;
    long lastTime=-1,currentTime,frameRate=40,delay=1500;
	public void run(){
		try{
			while(gameStart){

			     recycle();
        	     sleep(delay);
			}
		}catch(Exception e){
			e.printStackTrace();
		}

	}

	public boolean createRoom(Room room){
		try{
			if(rooms.size()>=MAX_ROOM_NUMBER)return false;
			if(!this.rooms.containsKey(room.roomId)){
				
				RacingRoom rroom = new RacingRoom(room.roomId,this,room.map,room.mode);
				if(!rroom.initPlayers(room.getUserNumber(),room.RS.getUids(),room.RS.getSids()))return false;
				this.rooms.put(room.roomId,rroom);
				rroom.roomCreateTime=System.currentTimeMillis();
				rroom.lastFrameStartTime=rroom.roomCreateTime;
				rroom.start();
				return true;
			}
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return false;
	}

	ArrayList<Integer> recycleList=new ArrayList<Integer> (); 


	public  void applyRecycle(int roomId){
		synchronized(recycleList){
			recycleList.add(roomId);
		}
	}
 

    private void recycle(){
		synchronized(recycleList){
			 
			for(Integer rid:recycleList){
				this.destroyRoom(rid);
			}
			recycleList.clear();
		} 	
    }
	public void destroyRoom(int roomId){
		
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		if(this.rooms.containsKey(roomId)){
			log.info("destroyRoom  room id ===="+roomId+"--"+sd.format(new java.util.Date()));
			rooms.remove(roomId);
			RoomManage.unlockRoom(roomId);
		}
		//remove user
	}

	
}
